package com.summer.container;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class HashMapTest {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InterruptedException {
		
		
		
		SafeCopyMap<String,String> hashMap = new SafeCopyMap<String,String>();
		hashMap.put("a", "a");
		hashMap.put("b", "b");
		hashMap.put("c", "c");
		hashMap.put("d", "d");
		
		new Thread(()->{
			for(int i=0;i<1000;i++) {
				hashMap.put(String.valueOf(i),String.valueOf(i));
			}
		}).start();
		
		Thread.sleep(1);
		
//		Iterator<Entry<String, String>> iterator = hashMap.entrySet().iterator();
		
//		HashMap<String,String> hashMap2 = new HashMap<String,String>();
		HashMap<String,String> hashMap2 = (HashMap<String, String>) hashMap.clone();
		
//		while(iterator.hasNext()){
//			Entry<String,String> e = iterator.next();
//			System.out.println(e.getValue());
////			iterator.remove();
//			hashMap2.put(e.getKey(), e.getValue());
//		}
		
		for(Entry<String, String> e : hashMap2.entrySet()){
			System.out.println(e.getValue());
//			hashMap.remove(e.getKey());
		}
		
		
	}
	
	
	public static class SafeCopyMap<K,V> extends HashMap<K,V> {

		private static final long serialVersionUID = 1L;
		
		ReentrantReadWriteLock rtLock = new ReentrantReadWriteLock();
		
		@Override
		public V put(K key, V value) {
			try{
				rtLock.writeLock().lock();
		        return super.put(key, value);
			} finally {
				rtLock.writeLock().unlock();
			}
	    }
		
		@Override
		public Object clone(){
			try{
				rtLock.readLock().lock();
				return super.clone();
			} finally {
				rtLock.readLock().unlock();
			}
		}
		
	}
	
}
